package com.xs.ahoi.hcxs.listener;

import android.content.Intent;
import android.support.v4.media.session.MediaSessionCompat;
import android.view.KeyEvent;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.Constants;
import com.xs.ahoi.hcxs.utils.PostDelayedUtil;
import com.xs.ahoi.hcxs.utils.TimerDownUtil;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;

/**
 * 耳机按钮监听
 */
public class HeadSetButtonListener extends MediaSessionCompat.Callback {

    @Override
    public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
        if (Intent.ACTION_MEDIA_BUTTON.equals(mediaButtonEvent.getAction())) {

            // 获得按键码
            KeyEvent event = mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (KeyEvent.ACTION_UP == event.getAction()) {
                switch (event.getKeyCode()) {
                    // 下一章
                    case KeyEvent.KEYCODE_MEDIA_NEXT:
//                            BookFactory.getInstance().doPageNextCatalog();
                        break;
                    case KeyEvent.KEYCODE_HEADSETHOOK:
                        if (BookFactory.getInstance().isPlaying()) {
                            stop();
                        } else {
                            start();
                        }
                        break;
                    case KeyEvent.KEYCODE_MEDIA_PLAY:
                        start();
                        break;
                    case KeyEvent.KEYCODE_MEDIA_PAUSE:
                        stop();
                        break;
                }
            }
        }
        return super.onMediaButtonEvent(mediaButtonEvent);
    }

    private void start() {

        // 如果距离上次定时结束时间相差60s内，则继续定时播放10分钟
        long timeOver = ConfigDao.getInstance().getTimeOver();
        if (System.currentTimeMillis() - timeOver < Constants.TIME_OVER_DELAY_MILLISECOND) {
            TimerDownUtil.getInstance().reContinue(Constants.TIME_OVER_RECONTINUE_SECOND);
            TtsUtil.getInstance().speakText("播放将在" + Constants.TIME_OVER_RECONTINUE_SECOND / 60 + "分钟后自动停止");
            PostDelayedUtil.doDelayed(() -> BookFactory.getInstance().startPlay(), 3000);
        } else {
            BookFactory.getInstance().startPlay();
        }

    }

    private void stop() {
        BookFactory.getInstance().stopPlay(true);
    }
}
